import { XCollection } from '@/utils/excel';
import { ITarget } from '../target/base/target';
import { Xbase, XDomain } from '@/ts/base/schema';
import { PlatformDomainBinding } from '@/ts/base/model';

export class DomainProvider {
  readonly target: ITarget;
  settingColl: XCollection<XDomain>;
  domainColl?: XCollection<PlatformDomainBinding & Xbase>;
  domainSettingCollName = 'domain-setting';

  constructor(target: ITarget) {
    this.target = target;
    this.settingColl = target.resource.genColl<XDomain>(this.domainSettingCollName);
  }

  async loadDomainSetting(): Promise<XDomain> {
    const settings = await this.settingColl.loadSpace({
      options: {
        match: {},
      },
    });

    let setting = settings.find((s) => s.isEnabled);
    if (!setting) {
      setting = settings[0];
    }
    if (!setting) {
      setting = {
        belongId: this.target.belongId,
        shareId: this.target.id,
        name: `[${this.target.name}] 平台域名配置`,
        typeName: '域名配置',

        domain: '',
        theme: {
          name: 'default',
          icons: {},
          styleVars: {},
        },
        staticFiles: [],
        isEnabled: true,
      } as Partial<XDomain> as any;
    }
    return setting!;
  }

  async saveDomainSetting(setting: XDomain) {
    await this.settingColl.replace(setting);
  }
}
